/*
 * @Author: Broin
 * @Date: 2021-12-29 10:18:49
 * @LastEditTime: 2021-12-29 10:18:50
 * @LastEditors: your name
 * @Description: 
 * @FilePath: /ac_interface/test/back_terminal.js
 * MADE BY BROIN
 */


/**用来实现多个webssh功能**/
const http = require('http').Server(app);
const io = require('socket.io')(http, {cors: true});
const utf8 = require('utf8');
const SSHClient = require('ssh2').Client;

const serverInfo = {
  host: '192.168.18.141',
  port: 22,
  username: 'root',
  password: '就不告诉你'
};

function createNewServer(machineConfig, socket) {
  var ssh = new SSHClient();
  let {msgId} = machineConfig;
  ssh
    .on('ready', function () {
      socket.emit(msgId, '\r\n*** ' + serverInfo.host + ' SSH CONNECTION ESTABLISHED ***\r\n');
      // ssh设置cols和rows处理界面输入字符过长显示问题
      ssh.shell({cols: machineConfig.cols, rows: machineConfig.rows}, function (err, stream) {
        if (err) {
          return socket.emit(msgId, '\r\n*** SSH SHELL ERROR: ' + err.message + ' ***\r\n');
        }
        socket.on(msgId, function (data) {
          stream.write(data);
        });
        stream.on('data', function (d) {
          socket.emit(msgId, utf8.decode(d.toString('binary')));
        }).on('close', function () {
          ssh.end();
        });
        socket.on('resize', function socketOnResize (data) {
          stream.setWindow(data.rows, data.cols);
        });
      })
    })
    .on('close', function () {
      socket.emit(msgId, '\r\n*** SSH CONNECTION CLOSED ***\r\n');
    })
    .on('error', function (err) {
      console.log(err);
      socket.emit(msgId, '\r\n*** SSH CONNECTION ERROR: ' + err.message + ' ***\r\n');
    }).connect(serverInfo);
}

io.on('connection', function (socket) {
  socket.on('createNewServer', function (machineConfig) {
    // 新建一个ssh连接
    console.log("createNewServer")
    createNewServer(machineConfig, socket);
  })

  socket.on('disconnect', function () {
    console.log('user disconnected');
  });
})

http.listen(5000, function () {
  console.log('listening on * 5000');
});